import java.util.Comparator;
import java.util.HashMap;
import java.util.PriorityQueue;
class Solution {
    //前K个高频元素
    public int[] topKFrequent(int[] nums, int k) {
        if (nums.length == 0 || k > nums.length) {
            return new int[0];
        }
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i])) {
                int val = map.get(nums[i]);
                map.put(nums[i], val + 1);
            } else {
                map.put(nums[i], 1);
            }
        }
        PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return map.get(o1) -map.get(o2);
            }
        });
        for(Integer num:map.keySet()){
            if(queue.size()<k){
                queue.offer(num);
               }else {
                if (map.get(num) > map.get(queue.peek())) {
                    queue.poll();
                    queue.offer(num);
                }
            }
        }
        int[] arr = new int[k];
        int count = 0;
        while (!queue.isEmpty()) {
            arr[count] = queue.poll();
            count++;
        }
        return arr;
    }
}